<?php

namespace app\http\Controllers\Manage;

use think\App;
use think\facade\Session;
use think\Request;
use app\common\lib\Captcha;
use app\models\manage\AuthModel;

class AuthController extends BaseController
{
    private $authModel;

    public function __construct(App $app, Request $request)
    {
        parent::__construct($app, $request);
        $this->authModel = new AuthModel();
    }

    /**
     * Note:登录页面
     * User:端木凌风
     * Date:2022-11-24 13:35
     * @return string
     */
    public function login()
    {
        return $this->view('default', [], self::TEMPLATE_TYPE_LOGIN);
    }

    /**
     * Note:登录
     * User:端木凌风
     */
    public function loginIn(Request $request)
    {
        $params = $request->param();
        $params['client_ip'] = $request->ip();
        $code = $params['captcha_code'] ?? '';
        if (!$code) {
            return apiResponse(STATUS_CODE_DATAERROR, '缺少图片验证码');
        }
        if (!Captcha::check($code, 'manage_login')) {
            return apiResponse(STATUS_CODE_DATAERROR, '图片验证码不正确');
        }
        $res = $this->authModel->loginIn($params);
        return apiResponse($res['status'], $res['msg']);
    }

    /**
     * Note:退出登录
     * User:端木凌风
     * Date:2022-11-24 13:35
     * @return \Illuminate\Http\JsonResponse
     */
    public function loginOut()
    {
        $this->authModel->loginOut();
//        Session::set('manage_admin', null);
        return apiResponse(STATUS_CODE_SUCCESS, 'success');
    }

    /**
     * 修改密码页面
     * @return string
     */
    public function editPasswordPage()
    {
        return $this->view('edit_password');
    }

    /**
     * 修改密码
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function updatePassword(Request $request)
    {
        $params = $request->param();
        $password = $params['new_password'] ?? '';
        $passwordConfirm = $params['confirm_password'] ?? '';
        $originPassword = $params['old_password'] ?? '';
        $res = $this->authModel->editPassword($this->accountId, $password, $passwordConfirm, $originPassword);
        if ($res['status'] == STATUS_CODE_SUCCESS) {
            $this->authModel->loginOut();
        }
        return apiResponse($res['status'], $res['msg'], $res['data']);
    }


    /**
     * Note:生成验证码
     * User:端木凌风
     * Date:2022-11-24 13:01
     * @return mixed
     */
    public function getCaptcha()
    {
        return $this->createCaptcha('manage_login', ['width' => 145, 'height' => 55, 'charset' => 1]);
    }

}